package org.vnl.platform.dk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/** 
 * 用來幫助建立dom4j的文件
 * 
 * @author Vaughan
 *
 */
public class Dom4jHelper {
    
    private static final Logger logger = Logger.getLogger(Dom4jHelper.class);

    private static Dom4jHelper instance;
    
    private Dom4jHelper() {
        
    }
    
    public static Dom4jHelper getInstance() {
        if (instance == null) {
            instance = new Dom4jHelper();
        }
        return instance;
    }
    
    public Document getDocument(String fileLocation) {
        File file = new File(fileLocation);
        if (file.exists()) {
            try {
                return getDocument(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                logger.error("Cannot open XML File", e);
                return null;
            }
        }
        InputStream in = null;
        in = this.getClass().getResourceAsStream(fileLocation);
        return getDocument(in);
    }
    
    public Document getDocument(InputStream in) {
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(in);
            return doc;
        } catch (DocumentException e) {
            logger.error("Cannot parse XML stream", e);
            return null;
        }
    }
    
}
